var api = require('../config/api.js');
var app = getApp();

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'ACCESS-Token': wx.getStorageSync('token')
      },
      success: function (res) {

        if (res.statusCode == 200) {

          if (res.data.code == 501) {
            //TODO 此处还需要优化
            // 清除登录相关内容
            try {
              wx.removeStorageSync('userInfo');
              wx.removeStorageSync('token');
            } catch (e) {
              // Do something when catch error
            }
            // 切换到登录页面
            wx.navigateTo({
              url: '/pages/auth/login/login'
            });
          } else if (res.data.code == 1) {
            resolve(res.data.obj);
          } else {
            // reject(res.errMsg);
            showErrorToast(res.data.msg);
          }
        } else {
          reject(res.data.msg);
        }

      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}

/**
 * wx.request的异步封装
 */
function requestNoToken(url, data = {}, method = "") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Accept': 'application/json',
      },
      success: function (res) {
        resolve(res.data);
      },
      fail: function (res) {
        reject(res)
      }
    })
  });
}

// util.requestNoToken(api.GetGoodInfomanage, {}, "").then(function (res) {
//   wx.showLoading({
//     title: '加载中',
//   })
//   if (res.success) {

//   }
// }).catch(function (res) {
//   console.log("获取数据失败！")
// })

/**
 * wx.request的异步封装
 */
function req(url, data = {}, method = "") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Accept': 'application/json',
        'ACCESS-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        resolve(res.data);
      },
      fail: function (res) {
        reject(res)
      }
    })
  });
}

// util.req(api.GetGoodInfomanage, {}, "").then(function (res) {
//   wx.showLoading({
//     title: '加载中',
//   })
//   if (res.success) {

//   }
// }).catch(function (res) {
//   console.log("获取数据失败！")
// })


//tabBar购物车数量提示
function buycarBar(no) {
  var num = JSON.stringify(wx.getStorageSync('carNum'))
  var lis = wx.getStorageSync("lists")
  if (num > 0) {
    wx.setTabBarBadge({
      index: 2,
      text: num
    })
  }
  if (no !== undefined) {
    if (no == 1) {
      wx.removeTabBarBadge({
        index: 2,
      })
    }
  }
  if (lis.length == 0) {
    wx.removeTabBarBadge({
      index: 2,
    })
    wx.setStorage({
      key: 'carNum',
      data: 0,
    })
  }
}


function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

// 显示繁忙提示
var showBusy = text => wx.showToast({
  title: text,
  icon: 'loading',
  duration: 10000
})
// 显示成功提示
var showSuccess = text => wx.showToast({
  title: text,
  icon: 'success'
})
// 一般错误提示
var showErr = text => wx.showToast({
  title: text,
  showCancel: false
})

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/icon_error.png'
  })
}
let getQueryString = function (url, name) {
  console.log("url = " + url)
  console.log("name = " + name)
  var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
  var r = url.substr(1).match(reg)
  if (r != null) {
    console.log("r = " + r)
    console.log("r[2] = " + r[2])
    return r[2]
  }
  return null;
}

function isEmpty(obj){
  if (typeof obj == "undefined" || obj == null || obj == "") {
    return true;
  } else {
    return false;
  }
}

module.exports = {
  formatTime,
  request,
  redirect,
  showErrorToast,
  requestNoToken,
  req,
  buycarBar,
  getQueryString: getQueryString,
  isEmpty,
  showBusy,
  showErr,
  showSuccess
}


